package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据访问层对象的具体实现,在实现类中借助JDBC借助直接访问数据库,
 * @Repository 是spring框架中定义一个描述数据层bean对象的注解
 */
@Repository //是一个特殊的Component对象
public class DefaultGoodsDao  implements  GoodsDao{

    @Autowired
    private DataSource dataSource;
    @Override
    public List<Map<String, Object>> findGoods() {
        Connection conn=null;
        Statement stmt=null;
        String sql="select * from tb_goods";
        ResultSet rs=null;
        try {
            //1.获取连接
            conn = dataSource.getConnection();
            //2.创建statement
            stmt = conn.createStatement();
            //3.发送sql
            rs = stmt.executeQuery(sql);
            //4.处理结果
            List<Map<String, Object>> list = new ArrayList<>();
            while (rs.next()) {//循环一次取一行,这个过程通常称之为行映射
                Map<String, Object> map = new HashMap<>();
                map.put("id", rs.getInt("id"));
                map.put("name", rs.getString("name"));
                map.put("remark", rs.getString("remark"));
                map.put("createdTime", rs.getTimestamp("createdTime"));
                list.add(map);
            }
            return list;
        }catch (SQLException e){
            e.printStackTrace();
            return null;
        }finally{
            //5.释放资源
            if(rs!=null)try{rs.close();}catch(SQLException e1){}
            if(stmt!=null)try{stmt.close();}catch(SQLException e1){}
            if(conn!=null)try{conn.close();}catch(SQLException e1){}
        }

    }
}